package com.atguigu.gmall.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.awt.image.RescaleOp;

@Slf4j
public class JSONs {
    static ObjectMapper objectMapper = new ObjectMapper();

    public static String objecttoString(Object obj) {
        String res = null;
        try {
            res = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象解析字符串失败");
        }
        return res;
    }

    public static <T> T stringToObj(String source, Class<T> targetClass) {
        T t = null;
        try {
            t = objectMapper.readValue(source, targetClass);
        } catch (JsonProcessingException e) {
            log.error("字符串转换为对象失败");
        }
        return t;
    }

    public static <T> T stringToObj(String source, TypeReference<T> typeReference) {
        T t = null;
        try {
            t = objectMapper.readValue(source, typeReference);
        } catch (JsonProcessingException e) {
            log.error("字符串转换为对象失败");
        }
        return t;
    }
}
